package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"sesm/models"
	// "strconv"
	"crypto/md5"
	"io"
	"time"
)

// Operations about object
type ClusterController struct {
	baseController
}

// @Title 获取集群列表
// @Description 获取所有集群配置
// @Success 200 {object} []models.ClustersConnectionInfo
// @Failure 403 objectId is empty
// @router /connections [get]
func (s *ClusterController) ConnectionList() {
	o := orm.NewOrm()
	qs := o.QueryTable("clusters_connection_info")
	qs.All(&models.Connections)
	s.normalReturn(&models.Connections)
}

// @Title 新增集群
// @Description 新增集群配置
// @Param   connection_info body json true  "连接信息，参照ClustersConnectionInfo"
// @Success 201 {string} create success !
// @Failure 422 create failed
// @router /connections [post]
func (s *ClusterController) AddConnection() {
	var cluster_info models.ClustersConnectionInfo
	err := json.Unmarshal(s.Ctx.Input.RequestBody, &cluster_info)
	if err != nil {
		s.errReturn(err, 422)
	}

	// gen cluster id
	h := md5.New()
	io.WriteString(h, cluster_info.ClusterName+cluster_info.ClusterType+cluster_info.ClusterRegion)
	cid := fmt.Sprintf("%x", string(h.Sum(nil)))
	cluster_info.ClusterId = cid[0:6]

	cluster_info.Addtime = time.Now().Format("2006-01-02 15:04:05")

	o := orm.NewOrm()
	id, err := o.Insert(&cluster_info)
	if err != nil {
		s.errReturn(err, 422)
	}
	s.normalReturn(id)
}

// @Title 删除集群
// @Description 删除集群配置
// @Param	cluster_id query string true  "集群id"
// @Success 204 {string} delete success !
// @Failure 422 delete failed
// @router /connections [delete]
func (s *ClusterController) DelConnection() {
	cluster_id := s.GetString("cluster_id")
	o := orm.NewOrm()
	num, err := o.Delete(&models.ClustersConnectionInfo{ClusterId: cluster_id}, "cluster_id")
	if err != nil {
		s.errReturn(err, 422)
	}
	s.normalReturn(num)
}
